package models

import "errors"

type SystemSource struct {
	Id          int       `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	Name        string    `json:"name" xorm:"not null comment('题目来源名称') VARCHAR(100)"`
	SubjectId        int    `json:"subjectId" xorm:"not null comment('学科主键') INT(11)"`
	Comment        string    `json:"comment" xorm:"not null comment('题目来源名称') VARCHAR(100)"`
}

//返回到客户端的内容
type ClientSource struct {
	Id          int       `json:"id" `
	Name        string    `json:"name" `

}

var systemsource = "system_source"
func(s *SystemSource) GetRow() bool {
	has, err := mEngine.Get(s)
	if err==nil &&  has  {
		return true
	}
	return false
}
func  (s *SystemSource) GetAll() ([]SystemSource,error) {

	var systemsources []SystemSource
	err:=mEngine.Find(&systemsources)
	return systemsources,err
}

func  (s *SystemSource) GetById(id int) (SystemSource,error) {

	var systemsources []SystemSource
	err:=mEngine.Table(systemsource).Where("id = ?",id).Find(&systemsources)
	if len(systemsources)==0 {
		return SystemSource{},errors.New("不存在该题目来源")
	}
	return systemsources[0],err
}

func  (s *SystemSource)GetBySubjectAndLevel(subjectId int,levelIds string)([]ClientSource,error){
	var clientsources []ClientSource

	err := mEngine.Table(systemsource).Distinct( systemsource+".id",systemsource+".name").
		Join("INNER", systemsourcelevel, systemsourcelevel+".source_id= "+systemsource+".id").
		Where(systemsource+".subject_id = ?", subjectId).
		Where(systemsourcelevel+".level_id in (?)", levelIds).
		Find(&clientsources)
	return clientsources,err
}

func  (s *SystemSource)GetBySubjectId(subjectId int)([]ClientSource,error){
	var clientsources []ClientSource

	err := mEngine.Table(systemsource).Distinct( systemsource+".id",systemsource+".name").
		Where(systemsource+".subject_id = ?", subjectId).
		Find(&clientsources)
	return clientsources,err
}


func (s *SystemSource) Add(levelIdsArr[] int) (int,error){
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return 0,err
	}
	//var uid int64
	_,err:=session.Insert(s)
	if err!=nil {
		return 0,err
	}

	for _,levelId:=range levelIdsArr {
		levelModel := SystemLevel{}
		levelModel.Id = levelId
		has := levelModel.GetRow()
		if !has {
			//如果学科不存在，忽略
			continue
		}

		sourceLevelModel := SystemSourceLevel{SourceId: s.Id, LevelId: levelId}

		has, err := session.Get(&sourceLevelModel)
		if err != nil {
			return 0, err
		}
		//如果来源阶段不存在，添加来源阶段
		if !has {
			_, err = session.Insert(&sourceLevelModel)
			if err != nil {
				return 0, err
			}
		}

	}
	return s.Id,session.Commit()
}

func (s *SystemSource) Update(levelIdsArr[] int) (int,error ){
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return 0,err
	}
	if _, err := mEngine.Where("id = ?", s.Id).Update(s); err != nil {
		return 0,err

	}

	sourceLevelModelForDelete := SystemSourceLevel{SourceId: s.Id}
	session.Delete(sourceLevelModelForDelete)

	for _,levelId:=range levelIdsArr {
		levelModel := SystemLevel{}
		levelModel.Id = levelId
		has := levelModel.GetRow()
		if !has {
			//如果阶段不存在，忽略
			continue
		}

		sourceLevelModel := SystemSourceLevel{SourceId: s.Id, LevelId: levelId}


		_,err := session.Insert(&sourceLevelModel)
		if err != nil {
			return 0, err
		}



	}

	return s.Id,session.Commit()
}
func (s *SystemSource) Delete() error {

	//TO: 将彻底删除所有相关的试题！

	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	//删除来源阶段信息
	/*
	sourceLevelModel:=SystemSourceLevel{}
	sourceLevelModel.SourceId=s.Id
	if _, err := mEngine.Where("source_id = ?", s.Id).Delete(sourceLevelModel); err != nil {
		return err

	}

	//删除试题相关信息（在数据库中设置了及联删除)
	if _, err := mEngine.Exec("DELETE  from "+systemquestion +" WHERE source_id=?" ,s.Id); err != nil {
		return err
	}
	*/

	//删除来源信息
	if _, err := mEngine.Where("id = ?", s.Id).Delete(s); err != nil {
		return err
	}

	//删除孤立的试卷
	if _, err :=mEngine.Exec("delete from "+userexam+" where not exists (select 1 from "+userexamquestion+" where "+userexamquestion+".exam_id ="+userexam+".id )"); err != nil {
		return err

	}
	return session.Commit()

}

